﻿using System;
using System.Configuration;
using AzureFacebook.Domain;
using Azure.Toolkit;
using Azure.Toolkit.Azure;
using AzureFacebook.Data.Sql;

namespace AzureFacebook.WorkerRole
{

    public class CommentProcessor : MessageProcessor<Comment>
    {
        public CommentProcessor()
            : base(QueueNames.CommentsQueue)
        {
        }

        static AzureFacebookDataContext CreateDataContext()
        {
            string connection = ConfigurationManager.ConnectionStrings["SqlAzure"].ConnectionString;
            return new AzureFacebookDataContext(connection);
        }

        public override void ProcessMessage(Comment msg)
        {

            this.SaveToSqlAzure(msg);

            this.SaveToTableStorage(msg);
           
        }

        public void SaveToSqlAzure(Comment msg)
        {
            using (var sqlRepository = new LinqToSqlRepository<CommentEntity>(CreateDataContext()))
            {
                sqlRepository.Insert(msg.MapToSqlData());
                sqlRepository.Commit();
            }
        }

        public void SaveToTableStorage(Comment msg)
        {
            AzureFacebook.Data.AddCommentCommand command = new AzureFacebook.Data.AddCommentCommand();
            command.Execute(msg);

        }
    }
}
